/**************************************************************/
/*             Java script for tau-mim gadget                 */
/**************************************************************/

/******************************************* 
* Utils static class
********************************************/
function Utils() {}

/**
* static public object gebi(string Id)
* getElementById
*/
Utils.gebi=function(id){ return (typeof(id)=="object"?id:document.getElementById(id));}

/**
* static public void setArray(string prefName, array<> arr)
* set an array to a userPref. Using JSON to walkaround a Google userPref bug at gadgets.prefs.setArray()
*/
Utils.setArray=function(prefName,arr){ if (!arr) arr=new Array; try{ var arrJSON=gadgets.json.stringify(arr); arrJSON=gadgets.util.escapeString(arrJSON); prefs.set(prefName,arrJSON); } catch (e){} return; }

/**
* static public array<> getArray(string prefName)
* get an array from a userPref. Using JSNO to walkaround a Google userPref bug.
*/
Utils.getArray=function(prefName){ var arrJSON = prefs.getString(prefName);  arrJSON=gadgets.util.unescapeString(arrJSON); if (arrJSON=="") return new Array; var arr; try{arr=gadgets.json.parse(arrJSON);  if (!arr) arr=new Array; }  catch (e) { arr=null; }  return arr; }

/**
* static public void makeCachedRequest(string Url, function(response) callback, opt params, int refreshInterval)
* a wrapper for the gadgets.io.makeRequest method, in order to force a cache refresh every <refreshInterval> seconds
*/
Utils.makeCachedRequest=function(url, callback, params, refreshInterval) {
	
	var ts = new Date().getTime();
	var sep = "?";
	if (refreshInterval && refreshInterval > 0) ts = Math.floor(ts / (refreshInterval * 1000));
	if (url.indexOf("?") > -1) sep = "&";
	url = [ url, sep, "nocache=", ts ].join("");
	gadgets.io.makeRequest(url, callback, params);
}

/******************************************* 
* Room class
********************************************/

Room.prototype.show=function(){
	this._visible=true;
	tabs.setSelectedTab(this.tab.getIndex());
}

Room.prototype.hide=function(){
	this._visible=false;
	tabs.setSelectedTab(0);
	tabs.removeTab(this.tab.getIndex());
	this._user.removeActiveRoom(this.id);
}

Room.prototype.isVisible=function(){
	return this._visible;
}

/**
* void deleteMe()
* Delete a room and its mesasages from the server
*/
Room.prototype.deleteMe=function(){
	var userId=this._user.getUserId();
	var userName = this._user.getUserName();
	var params = {};
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
	params[gadgets.io.RequestParameters.METHOD]=gadgets.io.MethodType.POST;
	params[gadgets.io.RequestParameters.POST_DATA]= gadgets.io.encodeValues({
		UserId:userId, 
		RoomId:this.id});
	
	var that=this;
	var callback= function(response){
		that.hide();
	}
	
	Utils.makeCachedRequest(GLOBAL_URL+"/RemoveRoom",callback, params,0);
}
/**
* void changeNickname(string nickname)
* Set a new nickname for the this room for a user at the server.
*/
Room.prototype.changeNickname=function(nickname){
	var userId=this._user.getUserId();
	var userName = this._user.getUserName();
	var params = {};
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
	params[gadgets.io.RequestParameters.METHOD]=gadgets.io.MethodType.POST;
	params[gadgets.io.RequestParameters.POST_DATA]= gadgets.io.encodeValues({
		NewNick:nickname, 
		UserId:userId, 
		RoomId:this.id});
	
	var that=this;
	var callback = function(response){
		that.refresh(true); //force refresh
	}
	Utils.makeCachedRequest(GLOBAL_URL+"/ChangeNick",callback, params,0);
}

/**
* void sendMessage(string message)
* Send a new message to the server for this room
*/
Room.prototype.sendMessage=function(message){
	var userId=this._user.getUserId();
	var userName = this._user.getUserName();
	var params = {};
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
	params[gadgets.io.RequestParameters.METHOD]=gadgets.io.MethodType.POST;
	params[gadgets.io.RequestParameters.POST_DATA]= gadgets.io.encodeValues({
		Message:message, 
		UserId:userId, 
		RoomId:this.id});
	var that=this;
	var callback = function(response){
		that.refresh(true);
	}
	Utils.makeCachedRequest(GLOBAL_URL+"/SendMessage",callback, params,0);
}

/**
* void sendYouTube(string message,string link)
* Send a new youtube to the server for this room
*/
Room.prototype.sendYouTube=function(message,link){
	var userId=this._user.getUserId();
	var userName = this._user.getUserName();
	var params = {};
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
	params[gadgets.io.RequestParameters.METHOD]=gadgets.io.MethodType.POST;
	params[gadgets.io.RequestParameters.POST_DATA]= gadgets.io.encodeValues({
		Headline:message, 
		Link:link, 
		UserId:userId, 
		RoomId:this.id});
	var that=this;
	var callback = function(response){
		that.refresh(true);
	}
	Utils.makeCachedRequest(GLOBAL_URL+"/SendYouTube",callback, params,0);
}

Room.prototype.deleteMessage=function(messageId){
	var userId=this._user.getUserId();
	var userName = this._user.getUserName();
	var params = {};
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
	params[gadgets.io.RequestParameters.METHOD]=gadgets.io.MethodType.POST;
	params[gadgets.io.RequestParameters.POST_DATA]= gadgets.io.encodeValues({
		MessageId:messageId, 
		UserId:userId});
	var that=this;
	var callback = function(response){
		that.refresh(true); //force refresh
	}
	Utils.makeCachedRequest(GLOBAL_URL+"/RemoveMessage",callback, params,0);
}

/**
* void sendPoll(string question, string[] answers)
* Send a new poll to the server for this room.
* Not tested yet.
*/
Room.prototype.sendPoll=function(question,answers){
	var userId=this._user.getUserId();
	var userName = this._user.getUserName();
	var params = {};

	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
	params[gadgets.io.RequestParameters.METHOD]=gadgets.io.MethodType.POST;
	params[gadgets.io.RequestParameters.POST_DATA]= gadgets.io.encodeValues({
		UserId:userId, 
		RoomId:this.id,
		Question:question,
		Answers:gadgets.json.stringify(answers)
		});
	var that=this;
	var callback = function(response){
		that.refresh(true); //force refresh
	}
	Utils.makeCachedRequest(GLOBAL_URL+"/CreatePoll",callback, params,0);
}


/**
* void statistics()
* Send a new poll to the server for this room.
* Not tested yet.
*/
Room.prototype.statistics=function(){
	var userId=this._user.getUserId();
	var userName = this._user.getUserName();
	var params = {};

	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
	params[gadgets.io.RequestParameters.METHOD]=gadgets.io.MethodType.GET;
	var getParams = [ ("UserId="+escape(userId)),("RoomId="+escape(this.id))].join("&");
	
	var that=this;
	var callback = function(response){
		showStatInfo(response.data[1]);		
	}
	var infoBox=Utils.gebi('statInfo');
	infoBox.innerHTML='';
	Utils.makeCachedRequest(GLOBAL_URL+"/GetRoomStatistics?"+getParams,callback, params,0);
	
}

function showStatInfo(userStats){
	var infoBox=Utils.gebi('statInfo');
	var line;
	for(var i=0;i<userStats.length;i++)
	{
		line="<span>"+userStats[i].nickname+" - "+userStats[i].numofmessages+"</span><br/>"
		infoBox.innerHTML+=line;
	}
	var data = new google.visualization.DataTable();
	data.addColumn('string', 'User');
	data.addColumn('number', 'Messages');
	data.addRows(userStats.length);
	for(var i=0;i<userStats.length;i++)
	{
		var numMessage=parseInt(userStats[i].numofmessages);
		data.setValue(i, 0, userStats[i].nickname);
		data.setValue(i, 1, numMessage);
	}
	var containerDiv=Utils.gebi('statChart');
	containerDiv.innerHTML="";
	var chart = new google.visualization.PieChart(containerDiv);
	chart.draw(data, {width: 265, height: 190, is3D: true,legend:'label'});
	
}	
/**
* void sendPollAnswer(string pollId, int answerNumber)
* Send the poll answer to the server. The answerNumber is the number of the question that was answered.
* Not tested yet.
*/
Room.prototype.sendPollAnswer=function(pollId,answerNumber){
	var userId=this._user.getUserId();
	var userName = this._user.getUserName();
	var params = {};

	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
	params[gadgets.io.RequestParameters.METHOD]=gadgets.io.MethodType.POST;
	params[gadgets.io.RequestParameters.POST_DATA]= gadgets.io.encodeValues({
		UserId:userId, 
		RoomId:this.id,
		MessageId:pollId,
		Answer:answerNumber
		});
	var that=this;
	var callback = function(response){
		that.refresh(true); // force refresh
	}
	Utils.makeCachedRequest(GLOBAL_URL+"/AnswerPoll",callback, params,0);
}

/**
* void inviteFriend(string friendId, string friendName, string friendEmail)
* Invite a friend using the openSocial API. FriendId is the openSocial friend Id.
*/
Room.prototype.inviteFriend=function(friendId,friendName,friendEmail){
	//var friendName = friends[friendId];
	var that=this;
	var userId=this._user.getUserId();
	var userName = this._user.getUserName();
	
	var params = {};
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
	params[gadgets.io.RequestParameters.METHOD]=gadgets.io.MethodType.POST;
	params[gadgets.io.RequestParameters.POST_DATA]= gadgets.io.encodeValues({
		MemberId:friendId, 
		MemberName:friendName,
		MemberEmail:friendEmail,
		UserId:userId, 
		RoomId:this.id});
	var onAddMember = function(obj){
		that.refresh(true); //force refresh
	}
	Utils.makeCachedRequest(GLOBAL_URL+"/AddMember",onAddMember, params,0);
	
	var that=this;
	var onMessage = function(obj){
		if (obj.hadError()){
			switch(obj.getErrorCode()) {
            case opensocial.ResponseItem.Error.NOT_IMPLEMENTED :
              break;
            default:
              break;
			};
			return;
		} 
	}
	var recipient = new Array();
	var message = new opensocial.newMessage("You are invited to my room - "+this.name); 
	message.setField(opensocial.Message.Field.TITLE,"MIM Invintation");
	message.setField(opensocial.Message.Field.TYPE,opensocial.Message.Type.NOTIFICATION);
	
	recipient.push(friendId);
	opensocial.requestSendMessage(recipient,message,onMessage);
	
}

/**
*  private void _getRoomName (function(Room) outCallback)	
* Get this room's name from the server, by the roomId, and run the callback function if defined.
*/
Room.prototype._getRoomName=function(outCallback){
	if (!this.id) { 
		name="Unknown";
		return;
	}
	var userId=this._user.getUserId();
	var userName = this._user.getUserName();

	var that=this;
	var inCallback=function(response){
		// if room does not exists
		if (response.rc!=200||!response.data) return false;
		var roomObj = response.data[0];
		that.name=roomObj.roomName;
		that.onwer=roomObj.owner
		that._createTab();
		if (outCallback) outCallback(that);
	}
		
	var params = {};
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
	params[gadgets.io.RequestParameters.METHOD]=gadgets.io.MethodType.GET;
	var getParams = [ ("RoomId="+escape(this.id)),("UserId="+escape(userId))].join("&");
	Utils.makeCachedRequest(GLOBAL_URL+"/GetRoomMessages?"+getParams, inCallback,params,0);
}


/**
* private void _createRoomId(function(Room) outCallback)
* Create a new room, create a new tab and set the room ID
*/
Room.prototype._createRoomId=function(outCallback){
	var userId=this._user.getUserId();
	var userName=this._user.getUserName();
	var that=this;
	var inCallback = function (response){	
		that.id=response.text;
		that.id = response.text; 
		that._createTab();
		if (outCallback) outCallback(that);
	}
		
	var params = {};
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
	params[gadgets.io.RequestParameters.METHOD]=gadgets.io.MethodType.POST;
	params[gadgets.io.RequestParameters.POST_DATA]= gadgets.io.encodeValues(
		{RoomName:this.name, 
		UserId:userId, 
		UserName:userName});
	Utils.makeCachedRequest(GLOBAL_URL+"/CreateRoom", inCallback,params,0);
}

/** 
*  private void _createTab()
* Create a tab for the new room
*/
Room.prototype._createTab=function(){
	var tabArray = tabs.getTabs();
	var tabId = tabs.addTab('<span class="tabName">'+this.name+'<input type="image" alt="[x]" title="Close this room" class="closeButton" id="'+this.id+
	'"src="http://tau-mim.googlecode.com/svn/trunk/gadget/images/closeButton.gif" onClick=\'hideRoomName("'+this.id+'"); return false;\'/></span>', {callback: this._onSelectTab(),index:tabArray.length-1});
	for (var i=0; i<tabArray.length; i++){
		if (tabArray[i].getContentContainer().id==tabId) this.tab=tabArray[i];
	}
	var nameContainer=this.tab.getNameContainer();
	value = nameContainer.innerHTML;
	html = "<span class='tablib_extension_left_unselected'>" + value+"</span>";
	nameContainer.innerHTML = html;
	this.tab.room=this;
}

Room.prototype._getMessages=function(){
	var that=this;
	tabId=that.tab.getContentContainer().id;
	
	if (!that.isVisible()) {
		//show the feed tab instead
		var tabArray = tabs.getTabs();
		tabArray[0].room.show();
		return false;
	}
	var userId=that._user.getUserId();
	var userName = that._user.getUserName();
				
	var readMessagesCallback=function(response){
		that._loadedMessages=0;
		if (response&&response.data&&response.data[0]&&response.data[1]){
			var messages = response.data[1];
			var header=response.data[0];
			if (messages.length>0){
				var timestamp=messages[0].timestamp;
				that.timestamp=timestamp;
			}
			that._loadedMessages=messages.length;
			that._messageRenderer(tabId,messages,false,false,header.owner);
			
		}
		var loadDiv=Utils.gebi('loadingContainer');
		loadDiv.style.display='none';
		
	}
			
	var params = {};
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
	params[gadgets.io.RequestParameters.METHOD]=gadgets.io.MethodType.GET;
	var getParams = [ ("RoomId="+escape(that.id)),("UserId="+escape(userId))].join("&");
	
	var loadDiv=Utils.gebi('loadingContainer');
	loadDiv.style.display='block';
	Utils.makeCachedRequest(GLOBAL_URL+"/GetRoomMessages?"+getParams, readMessagesCallback,params,0);
	/*
	enableSendingOptions();
	changeSelectedTab();
	*/
}

Room.prototype.refresh=function(force){
	var that=this;
	if (force) {
		that._getMessages();
		return;
	}
	var callback=function(response){
		if (response&&response.data!='0')
			that._getMessages();
	}
	var timestamp=that.timestamp;
	if (!timestamp) timestamp="";
	var params = {};
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
	params[gadgets.io.RequestParameters.METHOD]=gadgets.io.MethodType.GET;
	var getParams = [ ("RoomId="+escape(that.id)),("Time="+escape(timestamp))].join("&");
	Utils.makeCachedRequest(GLOBAL_URL+"/NumOfNewMessages?"+getParams, callback,params,0);
	
}
/**
* private void _onSelectTab()
* onSelect tab callback function. Retrive from the server messages for the room.
*/
Room.prototype._onSelectTab=function(){
	var that=this;
	return function(tabId){
		that.refresh(true);
		// Don't touch this IF - it works!
		if (this.room.isVisible()){
			enableSendingOptions();
			changeSelectedTab();
		}
	}
	
}

Room.prototype._getMoreMessages=function(){
	var that=this;

	var userId=that._user.getUserId();
	var userName = that._user.getUserName();
	var tabId=that.tab.getContentContainer(); 
				
	var readMessagesCallback=function(response){
		var messages = response.data[1];
		var header = response.data[0];
		if(messages!=null){
			that._messageRenderer(tabId,messages,true,false,header.owner); 
			that._loadedMessages+=messages.length;
		}
		var loadDiv=Utils.gebi('loadingContainer');
		loadDiv.style.display='none';
	}
		
	var params = {};
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
	params[gadgets.io.RequestParameters.METHOD]=gadgets.io.MethodType.GET;

	var getParams = [ ("RoomId="+escape(that.id)),("UserId="+escape(userId)),("Messages=10"),("Offset="+that._loadedMessages)].join("&");
	var loadDiv=Utils.gebi('loadingContainer');
	loadDiv.style.display='block';
	Utils.makeCachedRequest(GLOBAL_URL+"/GetRoomMessages?"+getParams, readMessagesCallback,params,0);
		
	
}

function getMoreMessages(){
	var selectedRoom=getSelectedRoom();
	if (selectedRoom) selectedRoom._getMoreMessages();
}

/**
* public Room(function(Room room) onCreate, User user, function(String tabId, Array<Messages> messages, Boolean AppendMode) messageRenderer, String name, String id)
* constractor. Name OR ID should be defined. 
* If name exists, then a new room will be created at the server.
* If Id exists, then the name will be retrived from the server.
* onCreate is a callback function for creating the object
* messageRenderer is a callback function to render messages.
*/
function Room(onCreate, user, messageRenderer, name, id){
	if (!user) return null;
	this._messageRenderer = messageRenderer;
	this._user=user;
	this._loadedMessages=0;
	this._visible=true;
	this.owner=true;
	this.timestamp="";
	if ((!name)&&(!id)) return null;
	if (!name){ 
		this.id=id;
		this._getRoomName(onCreate);
	} 
	
	if (!id) { 
		this.name=name;
		this._createRoomId(onCreate);
	} 
}


/**
* Feed tab - subclass of Room
*/
FeedRoom.prototype = new Room;

function FeedRoom(onCreate, user, messageRenderer, id){
	if (!user) return null;
	this._messageRenderer = messageRenderer;
	this._user=user;
	this._loadedMessages=0;
	this.id=id;
	this.owner=false;
	this._createFeed(onCreate);
}

FeedRoom.prototype._createFeed=function(outCallback){
	if (!this.id) { 
		name="Unknown";
		return;
	}
	var that=this;
	var userId=this._user.getUserId();
	var userName = this._user.getUserName();
	
	this.name=this.id;
	this._createTab();
	if (outCallback) outCallback(that);
}

/**
* private void _onSelectTab()
* onSelect tab callback function. Retrive from the server messages for the room.
*/
FeedRoom.prototype._onSelectTab=function(){
	var that=this;
	
	return function(tabId){
		var userId=that._user.getUserId();
		var userName = that._user.getUserName();
					
		var readMessagesCallback=function(response){
			var messages = response.data;
			if (that._messageRenderer)
				that._messageRenderer(tabId,messages,false,true,false);
				var loadDiv=Utils.gebi('loadingContainer');
				loadDiv.style.display='none';
				that._loadedMessages=messages.length;
		}
			
		var params = {};
		params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
		params[gadgets.io.RequestParameters.METHOD]=gadgets.io.MethodType.GET;
		var getParams = [("UserId="+escape(userId)),("UserName="+escape(userName))].join("&");
		var loadDiv=Utils.gebi('loadingContainer');
		loadDiv.style.display='block';

		// make feed request every 60 seconds
		Utils.makeCachedRequest(GLOBAL_URL+"/GetUserFeed?"+getParams, readMessagesCallback,params,0);
		disableSendingOptions();
		changeSelectedTab();
	}
	
}

/** 
*  private void _createTab()
* Create a tab for the new room
*/
FeedRoom.prototype._createTab=function(){
	var tabId = tabs.addTab(this.name, {callback: this._onSelectTab(),index:0});
	var tabArray = tabs.getTabs();
	for (var i=0; i<tabArray.length; i++){
		if (tabArray[i].getContentContainer().id==tabId) this.tab=tabArray[i];
	}
	var nameContainer=this.tab.getNameContainer();
	value = nameContainer.innerHTML;
	html = "<span class='tablib_extension_left_selected'>" + value+"</span>";
	nameContainer.innerHTML = html;
	
	this.tab.room=this;
}


FeedRoom.prototype._getMoreMessages=function(){

	var that=this;

	var userId=that._user.getUserId();
	var userName = that._user.getUserName();
	var tabId=that.tab.getContentContainer(); 
				
	var readMessagesCallback=function(response){
		var messages = response.data;

		that._messageRenderer(tabId,messages,true,true,false); 

		var loadDiv=Utils.gebi('loadingContainer');
		loadDiv.style.display='none';
		that._loadedMessages+=messages.length;
	}
		
	var params = {};
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
	params[gadgets.io.RequestParameters.METHOD]=gadgets.io.MethodType.GET;

	var getParams = [ ("RoomId="+escape(that.id)),("UserId="+escape(userId)),("Messages=10"),("Offset="+that._loadedMessages)].join("&");

	var loadDiv=Utils.gebi('loadingContainer');
	loadDiv.style.display='block';

	Utils.makeCachedRequest(GLOBAL_URL+"/GetUserFeed?"+getParams, readMessagesCallback,params,0);
		
	
}


	
/*******************************************
	User class
*******************************************/

User.prototype.refreshNonActiveRooms=function(){
		var that=this;
	while (that.nonActiveRooms.length>0) { that.nonActiveRooms.pop(); }
	
	for (var i=0;i<that.rooms.length;i++){
		var room=that.rooms[i];
		if (!that.isActiveRoom(room.roomId)) that.nonActiveRooms.push(room);
	}
}
User.prototype.getUserId=function(){return this._userId;}
User.prototype.getUserName=function(){return this._userName;}

/**
* private void _getUserRooms(function (User user) callback)
* get the list of rooms the user is member of from the server. After finishing, run the callback function, if defined.
*/
User.prototype._getUserRooms=function(callback){
	var that=this;
	var userId=that._userId;
	var userName=that._userName;
	
	var innerCallback=function(response){
		that.rooms=new Array;
		var rooms=response.data;
		if (rooms){
			for (var i=0;i<rooms.length;i++){
				var room=rooms[i];
				that.rooms.push({roomId:room.roomId,roomName:room.roomName});
			}
		}
		that.refreshNonActiveRooms();
		if (callback) callback(that);
	}
	
	var params = {};
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
	params[gadgets.io.RequestParameters.METHOD]=gadgets.io.MethodType.GET;
	var getParams = [("UserId="+escape(userId)),("UserName="+escape(userName))].join("&");
	
	Utils.makeCachedRequest(GLOBAL_URL+"/GetUserRooms?"+getParams, innerCallback,params,0);
}

User.prototype.removeRoom=function(roomId){
	var i;
	var _rooms = new Array;
	for (i=0;i<this.rooms.length;i++){
		if (this.rooms[i].roomId!=roomId) _rooms.push(this.rooms[i]);
	}
	this.rooms=_rooms;
	
	var _activeRooms = new Array;
	for (i=0;i<this.activeRooms.length;i++){
		if (this.activeRooms[i]!=roomId) _activeRooms.push(this.activeRooms[i]);
	}
	this.activeRooms=_activeRooms;
	this.refreshNonActiveRooms();
}
/**
* public void addRoom(String roomId, String roomName)
* add a new room to the list of existing rooms the user have. 
*/
User.prototype.addRoom=function(roomId,roomName){
	var room={roomId:roomId,roomName:roomName};
	this.rooms.push(room);
	this.refreshNonActiveRooms();
}

User.prototype.isRoomExists=function(roomId){
	for (var i=0;i<this.rooms.length;i++){
		if (this.rooms[i].roomId==roomId) return true;
	}
	return false;
}
/**
* public void addActiveRoom(String roomId)
* add a roomId to the list of opened rooms
*/
User.prototype.addActiveRoom=function(roomId){
	if (!this.isActiveRoom(roomId)) 
		this.activeRooms.push(roomId);
	this.refreshNonActiveRooms();
}

/**
* public void removeActiveRoom(String roomId)
* remove this roomId from the list of open rooms
*/
User.prototype.removeActiveRoom=function(roomId){
	var arr=new Array;
	for (var i=0;i<this.activeRooms.length;i++){
		if (this.activeRooms[i]!=roomId) arr.push(this.activeRooms[i]);
	}
	this.activeRooms=arr;
	this.refreshNonActiveRooms();
}

/**
* public boolean isActiveRoom(String roomId)
* return true iff the roomId has an open tab now
*/
User.prototype.isActiveRoom=function(roomId){
	var that=this;
	for (var i=0;i<this.activeRooms.length;i++){
		var room=this.activeRooms[i];
		if (room==roomId) 
			return true;
	}
	return false;
}

User.prototype.fetchEmails=function(){
	var params = {};
	var that=this;
    var url = 'http://www.google.com/m8/feeds/contacts/default/full?max-results=500';
	var callback=function(response){
		
		if (response.oauthApprovalUrl) {
            var popup = shindig.oauth.popup({
				destination: response.oauthApprovalUrl,
				windowOptions: null,
				onOpen: function() {  },
				onClose: function() { that.fetchEmails(); }
			});
			var personalize = document.getElementById('personalize');
			personalize.onclick = popup.createOpenerOnClick();
			$("#approveWrap").dialog({ autoOpen: false, modal: true ,bgiframe: true} );
			$("#approveClose").click(function(){$("#approveWrap").dialog("close"); });
			
			$("#approveWrap").dialog("open");
        } else {
			$("#approveWrap").dialog("close");
			if (response.feed) {
				list = response.feed.entry;
				for(var i = 0; i < list.length; i++) {
					var entry = list[i];
					if(entry.gd$email&&entry.gd$email[0]&&entry.gd$email[0].address){
						var emailEntry=new Object;
						emailEntry.email=entry.gd$email[0].address;
						emailEntry.name=entry.title.$t;
						that.friendsEmails.push(emailEntry);
						//var email=entry.gd$email[0].address;
						//that.friendsEmails.push(email);
					}
				}
			}
        }
	}

	var service = new google.gdata.contacts.ContactsService('MIM');
    service.useOAuth('google');
    service.getContactFeed(url, callback, callback);
}

/**
* public User(Array<String> activeRooms, function(User user) onCreate)
* Constractor. activeRooms is an array of roomId that were open in the last session
* onCreate is a callback function that called after the object was created.
* The constractor gets the viewer Idand viewer's friend from the container, and loads the list of rooms that the user is memeber in from the server
*/
function User(activeRooms,onCreate){
	var that=this;
	that.loggedIn=true;
	this.activeRooms = [];
	
	if (activeRooms){
		for (var i=0;i<activeRooms.length;i++){
			var activeRoom = activeRooms[i];
			var found=false;
			for (var j=0; j<this.activeRooms.length; j++){
				if (activeRoom==this.activeRooms[j]){
					found=true;
					break;
				}
			}
			if (!found) this.activeRooms.push(activeRoom);
		}
	}
	this.nonActiveRooms=[];
	var callback=function(dataResponse) {
		
		var messageSupport=opensocial.getEnvironment().supportsField(opensocial.Environment.ObjectType.MESSAGE,opensocial.Message.Field.TITLE);
		
		// Will be true on Orkut, will be false on iGoogle
		if (!messageSupport) that.fetchEmails();
		
		var viewerObj = dataResponse.get('get_viewer').getData();
		
		// User is not logged in
		if (!viewerObj){
			that.loggedIn=false;
			if (onCreate) onCreate(that);
			return;
		}
		var friendsObj = dataResponse.get('get_friends').getData();
		that.thumbnail=viewerObj.getField(opensocial.Person.Field.THUMBNAIL_URL);
		that._userId = viewerObj.getId();
		that._userName = viewerObj.getDisplayName();
		that.friendsEmails=new Array;
		that.friendsObj=friendsObj;
		that.friends=new Array;
		that.rooms=new Array;
		friendsObj.each(function(person) {
			if (person.getId()){
				var friend = new Object;
				friend.id=person.getId();
				friend.name=person.getDisplayName(); 
				friend.thumbnail=person.getField(opensocial.Person.Field.THUMBNAIL_URL);
				
				friend.email=null;
				that.friends[person.getId()]=friend;
			}
		});
				
		that._getUserRooms(function(){if (onCreate) onCreate(that);});
	}
	

	var idspec = opensocial.newIdSpec({ "userId" : "VIEWER", "groupId" : "FRIENDS" });
	var req = opensocial.newDataRequest();
	req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), "get_viewer");
	req.add(req.newFetchPeopleRequest(idspec), "get_friends");
	req.send(callback);
}



/*******************************************
	Gadget JS
********************************************/

function isSandbox(){
	var result=true;
	try {
        var e = opensocial.getEnvironment();
	} catch(e) {
		result=false;
	}
	return result;
}

// Consts, set by hidden user prefs
var GLOBAL_URL; 
var regularRefresh;
var feedRefresh; 

// global opensocial/gadget objects
var user;
var tabs;
var prefs;
var intervalId;


//if (gadgets&&gadgets.util&&opensocial){
if (isSandbox()){
	// Call init function to initialize and display tabs.
	gadgets.util.registerOnLoadHandler(init);
} else {
	//show legacy warning.
	$(document).ready(function(){ 
		$('#startLoadingContainer').hide();
		$('#notSupportedDiv').show();
		$('#mainDiv').hide();; 
	});

}



function createPlus(){
	tabs.addTab("<span  id='plusDivLeftImage' class='tablib_extension_left_unselected' onclick='toggleAddRoom()'><span title='Create or open rooms' id='plusHeaderContainer' ></span><span id='plusText'>+</span></span>","addWrap",null);
	$("#addWrap").removeClass("tablib_content_container");
	tabsList = tabs.getTabs();
    var tab=tabsList[0];//only tab created so far
	var plusHeader=tab.getNameContainer();

	plusHeader.onclick=function(){};
	//plusHeader.style.width="8px";
	
	
}

function toggleAddRoom(){
	$("#addWrap").slideToggle("slow");
	renderRoomList(user);	
	return false;
}


function checkScrollEnd(){
	var objDiv = document.getElementById("divExample");
	objDiv.scrollTop = objDiv.scrollHeight;
}


function togglePoll(){
	$("#addPoll").dialog("open");
}
function showStatistics(){
	var selectedRoom=getSelectedRoom();
	selectedRoom.statistics();
	$("#statView").dialog("open");
}
function showVideo(){
	$("#sendYouTube").dialog("open");
}

function setScrollEvent(tabId){
	$('#'+tabId).scroll(function(){
		var scrollTopSize=this.scrollTop;
		var scrollHeightSize=this.scrollHeight;
		var offsetHeightSize=this.offsetHeight;
		if (scrollHeightSize-scrollTopSize==offsetHeightSize){getMoreMessages();}
	});
}

function renderRoomList(userObj){
	$('#roomList').unautocomplete();
	$('#roomList').remove();
	
	if (userObj.nonActiveRooms.length==0){
		$('#roomListWrap').append('<span id="roomList">No unopened rooms!</span>');
		return false;
	}
	
	$('#roomListWrap').append('<input id="roomList" type="text" />');
	
	$('#roomList').autocomplete(userObj.nonActiveRooms, {
				minChars: 0,
				matchContains: true,
				width:280,
				autoFill: false,
				formatItem: function(row, i, max) {
					return row.roomName;
				},
				formatMatch: function(row, i, max) {
					return row.roomName;
				},
				formatResult: function(row) {
					return row.roomId;
				}
		}
	);
	$('#roomList').result(function(event, data, formatted) {
		if (data){
			$(this).val(data.roomName);
			loadRoom(data.roomId);
			toggleAddRoom();
			$(this).val("");
		}
	});
	
}
/***********************************************************************************************/

function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function sendPollAnswer(btnObj,pollId){
	var answer=getCheckedValue(document.getElementsByName(pollId));
	// Poll answer number is 1 based index, while the value above is 0 based.
	answer++;
	
	btnObj.disabled=true;
	var selectedRoom=getSelectedRoom();
	selectedRoom.sendPollAnswer(pollId,answer);
}

//TODO:check after midnight (now is 00:15 and message from 21:00 )
function humane_date(date_str){
	var time_formats = [
		[60, 'Just Now'],
		[90, '1 Minute'], // 60*1.5
		[3600, 'Minutes', 60], // 60*60, 60
		[5400, '1 Hour'], // 60*60*1.5
		[86400, 'Hours', 3600], // 60*60*24, 60*60
		[129600, '1 Day'], // 60*60*24*1.5
		[604800, 'Days', 86400], // 60*60*24*7, 60*60*24
		[907200, '1 Week'], // 60*60*24*7*1.5
		[2628000, 'Weeks', 604800], // 60*60*24*(365/12), 60*60*24*7
		[3942000, '1 Month'], // 60*60*24*(365/12)*1.5
		[31536000, 'Months', 2628000], // 60*60*24*365, 60*60*24*(365/12)
		[47304000, '1 Year'], // 60*60*24*365*1.5
		[3153600000, 'Years', 31536000], // 60*60*24*365*100, 60*60*24*365
		[4730400000, '1 Century'], // 60*60*24*365*100*1.5
	];
	var time = Date.parse(date_str),
		dt = new Date,
		seconds = ((dt - new Date(time)) / 1000),
		token = ' Ago',
		i = 0,
		format;

	if (seconds < 0) {
		seconds = Math.abs(seconds);
		token = '';
	}


	while (format = time_formats[i++]) {
		if (seconds < format[0]) {
			if (format.length == 2) {
				return format[1] + (i > 1 ? token : ''); // Conditional so we don't return Just Now Ago
			} else {
				return Math.round(seconds / format[2]) + ' ' + format[1] + (i > 1 ? token : '');
			}
		}
	}

	// overflow for centuries
	if(seconds > 4730400000)
		return Math.round(seconds / 4730400000) + ' Centuries' + token;

	return date_str;
}

function openRoom(roomId){
	if (user.isActiveRoom(roomId)){
		tabsList = tabs.getTabs();
		for (var i=0;i<tabsList.length; i++){
			var tab=tabsList[i];
			if (tab.room.id==roomId){
				 tab.room.show();
				 break;
			}
		}
	} else {
		loadRoom(roomId);
	}
	return false;
}

 function escapeHTML(str) {
	 var replacedStr=str.replace(/</g,"&lt;");
	 replacedStr=replacedStr.replace(/\n/g,"<br/>");
	 return replacedStr;
 } 
function renderGeneralMessages(tabId,messages,boolAppend,isFeedRender,isOwner){
	if (!messages) return;
	if (!boolAppend) boolAppend=false;
	if (!isFeedRender) {
		changeResreshTime(regularRefresh);
	} else {
		changeResreshTime(feedRefresh);		
	}
	
	
	
	Utils.gebi('deleteButton').style.visibility=(isOwner)?'visible':'hidden';
	
	var tabContainer = Utils.gebi(tabId);
	var html = [];
	var polls=[];
	var videos=[];
	var deleteButtons=[];
	for (var i=0;i<messages.length;i++){
		var message=messages[i];
		var messageType=(message.type)?message.type:'regular';
		var timeString=message.timestamp.split(".")[0] + " UTC";
		var date = Date.parse(timeString);
		var messageUser = message.username;
		var messageNickname = message.nickname
		var messageRealName = (user.friends[messageUser])?user.friends[messageUser].name:messageNickname;
		
		var selfUser = (messageUser==user.getUserId());
		messageRealName = (selfUser&&!isFeedRender)?"Click to change your nickname":messageRealName;
		
		var userImage=(user.friends[messageUser]&&user.friends[messageUser].thumbnail)?user.friends[messageUser].thumbnail:'';
		if (selfUser&&user.thumbnail) userImage=user.thumbnail;
		
		html.push('<div class="messageContainer">');
		
		if (userImage!='') html.push('<img src="'+userImage+'" class="thumbnailClass" />');
		html.push("<span class='messageName' title='"+messageRealName+"'>");
		if (selfUser&&!isFeedRender) html.push("<a href='#' onclick='changeNickname(true)'>");
		html.push(escapeHTML(messages[i].nickname));
		if (selfUser&&!isFeedRender) html.push("</a>");
		
		if (isFeedRender){
			html.push("</span>");
			html.push('<span> wrote in room </span>');
			var funStr="openRoom('"+messages[i].roomId+"')";
			html.push('<a href="#" onclick="'+funStr+'" title="Open this room">'+escapeHTML(messages[i].roomName)+':</a>');
		}
		else
			html.push(":</span>");
			
		switch (messageType) {
			case "regular":
				html.push("<div class='messageText'>"+escapeHTML(messages[i].comment)+"</div>");
				break;
			case "pollQuestion":
				html.push("<div class='pollQuestionContainer'>");
				
				if (isFeedRender) html.push('A new poll - ');
				
				html.push("<span class='pollQuestion'>"+escapeHTML(messages[i].question)+"</span>");
				if (!isFeedRender){
					var answers=messages[i].answers;
					for (var j=0;j<answers.length;j++){
						html.push("<div class='pollQuestionContant'>");
						html.push('<input class="pollAnswerRadio" type="radio" name="'+messages[i].id+'" value='+j+'>');
						html.push("<span class='pollAnswer'>"+escapeHTML(answers[j])+"</span>");
						html.push("</div>");
						
					}
					html.push('<input class="pollAnswerButton" type="button" value="Submit" onclick="sendPollAnswer(this,')
					html.push("'"+messages[i].id+"');");
					html.push('" value="Submit" />');
				}
				html.push('</div>');
				break;
			case "pollResult":
				html.push("<div class='pollResultContainer'><span class='pollResultName'>");
				if (isFeedRender) html.push('A poll - ');
				html.push(escapeHTML(messages[i].question) +"?</span>");
				
				if (!isFeedRender){
					var chartId='chart_div'+messages[i].id;
					if (messages[i].roomId) chartId+=messages[i].roomId
					html.push("<div class='pollResultChart' id='"+chartId+"'></div>");
					polls.push(messages[i]);
				}
				html.push('</div>');
				break;
			case "youTube":
				html.push("<div class='videoContainer'><div class='videoName'>");
				if (isFeedRender) html.push("A new YouTube Link -");
				html.push(escapeHTML(messages[i].Headline) +"</div>");
				
				if (!isFeedRender){
					var videoIdDiv='video_div'+messages[i].id;
					if (messages[i].roomId) videoIdDiv+=messages[i].roomId
					html.push("<div class='videoEmbeded' id='"+videoIdDiv+"'>You need Flash player 8+ and JavaScript enabled to view this video.</div>");
					videos.push(messages[i]);
				}
				html.push('</div>');
				break;
		}
		html.push('<div class="messageOptionsContainer">');
		if (selfUser&&!isFeedRender){
			deleteButtons.push(messages[i].id);
			var deleteButtonId='deleteBtn'+messages[i].id;
			//if (isFeedRender) deleteButtonId+='feedTab';
			html.push("<input type='image' id='"+deleteButtonId+"' messageId='"+messages[i].id+"' class='trashButton' alt='delete' title='Delete this message' src='http://tau-mim.googlecode.com/svn/trunk/gadget/images/trash.gif' />");
		}
		
		html.push("<span class='messageDate' title='"+date+"'>"+humane_date(date)+"</span>");
		html.push('</div>');
		html.push('</div>');
	}
	
	if(boolAppend){
		var tempDiv=document.createElement('div');
		tempDiv.innerHTML=html.join('');
		while (tempDiv.firstChild) tabContainer.appendChild(tempDiv.firstChild);
	}
	else
		tabContainer.innerHTML=html.join('');

	//Render the polls, after the tab is ready
	for (var i=0;i<polls.length;i++){
		loadPolls(polls[i])
	}
	
		//Render the polls, after the tab is ready
	for (var i=0;i<videos.length;i++){
		loadVideos(videos[i])
	}

	//Create events for deleting messages
	for (var i=0;i<deleteButtons.length;i++){
		var deleteId=deleteButtons[i];
		var deleteButtonId='deleteBtn'+deleteId;
		//if (isFeedRender) deleteButtonId+='feedTab';
		
		$('#'+deleteButtonId).click(function(){
			var msgId=$(this).attr('messageId');
			deleteMessage(msgId);
		});
		$('#'+deleteButtonId).confirm({
			wrapper:'<span class="messageDeleteConfirm"></span>',
			dialogShow:'fadeIn',
			dialogSpeed:'slow',
			msg:'Are you sure? ',
			timeout:3000
		});
	}
		

}

function loadRoom(roomId){
	var onCreate=function(roomObj){
		user.addActiveRoom(roomObj.id);	
		var tabId=roomObj.tab.getContentContainer().id;
		setScrollEvent(tabId);
		roomObj.show(); 
	}
	var room=new Room(onCreate,user,renderGeneralMessages,null,roomId);
	var roomsArr=Utils.getArray("rooms");
	roomsArr.push(roomId);
	Utils.setArray("rooms",roomsArr);
}

function getSelectedRoom(){
	var tab=tabs.getSelectedTab();
	if (tab.room) return tab.room;
	return null;
}

function refreshTab(force){
	var selectedRoom=getSelectedRoom();
	if (selectedRoom) selectedRoom.refresh(force); //force refresh
}

// Create a new room.
function addRoom(){
	var roomName=Utils.gebi('create_room_form').elements['room'].value;
	Utils.gebi('create_room_form').elements['room'].value='Create a room';
	var room;
	var onCreate=function(roomObj){
		user.addActiveRoom(roomObj.id);
		user.addRoom(roomObj.id,roomObj.name);
		var tabId=roomObj.tab.getContentContainer().id;
		setScrollEvent(tabId);
		roomObj.show();
	}
	room = new Room(onCreate,user,renderGeneralMessages,roomName,null);
	return false;
}

// Send a message.
function sendMessage(){
	var messageObj=Utils.gebi('send_message_form').elements['messageInputText']
	var messageText=messageObj.value;
	messageObj.value='Message';
	$("#messageInputText").removeClass("activeWrite").addClass("nonActiveWrite");
	var selectedRoom=getSelectedRoom();
	if (selectedRoom) selectedRoom.sendMessage(messageText);
	return false;
}
// Send a youtube.
function sendYouTube(messageText,link){
	var selectedRoom=getSelectedRoom();
	if (selectedRoom) selectedRoom.sendYouTube(messageText,link);
	return false;
}

// Delete a message
function deleteMessage(messageId){
	var selectedRoom=getSelectedRoom();
	if (selectedRoom) selectedRoom.deleteMessage(messageId);
	return false;
}

function inviteFriendWithEmail(){
	var friendId = $('#tbHiddenFriends').val();
	var friendName = $('#tbFriends').val();
	var friendEmail=$('#tbFriendEmail').val();
	var selectedRoom=getSelectedRoom();

	if (selectedRoom) selectedRoom.inviteFriend(friendId,friendName,friendEmail);

	$('#tbFriendEmail').val("");
	$('#tbHiddenFriends').val("");
	$('#tbFriends').val("");

	$("#emailsWrap").dialog( 'close' );
	return false;
}

function inviteFriend(){
	var friendId = $('#tbHiddenFriends').val();
	var friendName = $('#tbFriends').val();
	var friendEmail=user.friends[friendId].email;
	
	if ((!friendEmail||friendEmail=='')&&user.friendsEmails.length>0){
		$('#tbFriendEmail').autocomplete(user.friendsEmails, {
				minChars: 0,
				matchContains: true,
				width:280,
				autoFill: false,
				formatItem: function(row, i, max) {
					return "\"" + row.name + "\" [" + row.email + "]";
				},
				formatMatch: function(row, i, max) {
					return row.name + " " + row.email;
				},
				formatResult: function(row) {
					return row.email;
				}
		});

		
		$("#emailsWrap").dialog( 'open' );
		
		return false;
	} else {
		var selectedRoom=getSelectedRoom();
		
		if (selectedRoom) selectedRoom.inviteFriend(friendId,friendName,friendEmail);
		
		$('#tbFriendEmail').val("");
		$('#tbHiddenFriends').val("");
		$('#tbFriends').val("");
		return false;
	}
	 return false;
}

function changeNickname(nick){
	if ((typeof nick)=='boolean'){
		$('#nicknameChange').dialog(nick?'open':'close');
		return false;
	}
	if (nick=='') {
		$('#nicknameChange').dialog('close');
		return false;
	}
	
	var selectedRoom=getSelectedRoom();
	if (selectedRoom) selectedRoom.changeNickname(nick);
	$('#nicknameChange').dialog('close');
	return false;
}

function hideRoomName(roomId){
	var tabArray = tabs.getTabs();
	for (var i=0; i<tabArray.length; i++){
		var tab=tabArray[i];
		if (tab.room.id==roomId){
			tab.room.hide();
			break;
		}
	}
	
	var roomsArr=Utils.getArray("rooms");
	var newRoomArr=[]
	for (var i=0;i<roomsArr.length;i++){
		var r=roomsArr[i];
		if (r!=roomId) newRoomArr.push(r);
	}
	Utils.setArray("rooms",newRoomArr);
}

function removeRoom(cont){
	if (!cont){
		$("#deleteRoomDialog").dialog("open");
		return false;
	} 
	$("#deleteRoomDialog").dialog("close");
	var selectedRoom=getSelectedRoom();
	if (!selectedRoom) return;
	
	user.removeRoom(selectedRoom.id);
	selectedRoom.deleteMe();
	
}

function sendPoll()
{
	var questionObj=Utils.gebi('question');
	var question='';
	if (questionObj.flag) question=questionObj.value;
	var answers=[];
	var answersIds=['answer1','answer2','answer3','answer4','answer5'];
	
	for (i=0;i<answersIds.length;i++){
		var answerCheckObj=Utils.gebi(answersIds[i]+'Check');
		if (answerCheckObj.checked){
			var answerObj=Utils.gebi(answersIds[i]);
			answers.push(answerObj.value);
		}
	}
	if (validatePoll(question,answers)){
		var selectedRoom=getSelectedRoom();
		selectedRoom.sendPoll(question,answers);
		$("#addPoll").dialog("close");
	}
	return false;
}

function clearPollForm(){
	var answersIds=['answer1','answer2','answer3','answer4','answer5'];
	for (i=0;i<answersIds.length;i++){
		var answerObj=Utils.gebi(answersIds[i]);
		answerObj.flag=false;
		answerObj.changedFlag=false;
		answerObj.value='Answer';
		var answerCheckObj=Utils.gebi(answersIds[i]+'Check');
		answerCheckObj.checked=false;
	}
	var questionObj=Utils.gebi('question');
	questionObj.value='Question';
	questionObj.flag=false;
	questionObj.changedFlag=false;
}

function validatePoll(question,answers){
	if (question=='') {
		alert('Missing question!');
		return false;
	}
	if (answers.length<2) {
		alert('Poll have to have at least 2 answers.');
		return false;
	}
	
	for (i=0;i<answers.length;i++){
		if (answers[i]=='') {
			alert('Empty answer exists!');
			return false;
		}
	}
	return true;
}
function closePollWindow()
{
	clearPollForm();
	setVisible("addPoll");
}
function minimizeWindow()
{
	obj = Utils.gebi('inviteWrap');
	obj.style.height = (obj.style.height=="20px")?"80px":"20px";
	obj.style.width = (obj.style.height=="40px")?"130px":"40px";
}

//disable all the elemets for interactivity
function disableSendingOptions()
{
	Utils.gebi("refreshButton").style.visibility="hidden";
	Utils.gebi('deleteButton').style.visibility='hidden';
	Utils.gebi("addPollButton").style.visibility="hidden";
	Utils.gebi("statisticsButton").style.visibility="hidden";
	Utils.gebi("videoButton").style.visibility="hidden";
	
	Utils.gebi("inviteWrap").style.visibility="hidden";
	Utils.gebi("sendWrap").style.visibility="hidden";
	$(".tablib_content_container").height("350px");
	
}
function enableSendingOptions()
{
	Utils.gebi("refreshButton").style.visibility="visible";
	Utils.gebi('deleteButton').style.visibility='hidden'; // This is enabled only by room renderer
	Utils.gebi("addPollButton").style.visibility="visible";
	Utils.gebi("statisticsButton").style.visibility="visible";
	Utils.gebi("videoButton").style.visibility="visible";
	Utils.gebi("inviteWrap").style.visibility="visible";
	Utils.gebi("sendWrap").style.visibility="visible";
	$(".tablib_content_container").height("300px");
}

function changeResreshTime(interval){
	if (intervalId) clearInterval(intervalId);
	intervalId=setInterval( "refreshTab()", interval*1000 );
	return false;
}
function loadVideos(videoData){
	var tempDivElem='video_div'+videoData.id;
	if (videoData.roomId) tempDivElem+=videoData.roomId

	var videoId=videoData.link;
	
	var params = { allowScriptAccess: "always", bgcolor: "#cccccc" ,wmode:"transparent"};
	var atts = { id: tempDivElem };
	swfobject.embedSWF("http://www.youtube.com/v/"+videoId+"&enablejsapi=1",tempDivElem,"200", "200", "8", null, null, params, atts);
}

function loadPolls(pollData){
	var tempDivElem='chart_div'+pollData.id;
	if (pollData.roomId) tempDivElem+=pollData.roomId

	var tempDataElem=pollData.answers;
	var tempPollName=pollData.question;
	var data = new google.visualization.DataTable();
	data.addColumn('string', 'Answer');
	data.addColumn('number', 'Votes');
	data.addRows(tempDataElem.length);
	for (var j=0;j<tempDataElem.length;j++){
		var answer=tempDataElem[j].answer;
		var count=parseInt(tempDataElem[j].count);
		data.setValue(j, 0,answer);
		data.setValue(j, 1,count);
	}
	
	var divElem=Utils.gebi(tempDivElem);
	var chart = new google.visualization.ColumnChart(divElem);
	chart.draw(data, {width: 200, height: 140+tempDataElem.length*20, is3D: true,legend:"none"});
}


function changeSelectedTab() {
  if (document.getElementById("tabsWrap_header")) {
	  var tabHeaders = document.getElementById("tabsWrap_header").rows[0].cells;
	  for (var i=0;i<tabHeaders.length;i++){
		if (tabHeaders[i].className && tabHeaders[i].className.match(/tablib_selected/)) {
		  if (tabHeaders[i].childNodes[0].className) {
			tabHeaders[i].childNodes[0].className = "tablib_extension_left_selected";
		  }
		}
		if (tabHeaders[i].className !== undefined && tabHeaders[i].className.match(/tablib_unselected/)) {
		  if (tabHeaders[i].childNodes[0].className) {
			tabHeaders[i].childNodes[0].className = "tablib_extension_left_unselected";
		  }
		}
	  }
	} 
}

function getVideoIdFromString(str)
{
	var subString=str.split("v=");
	if(subString.length>1){
		var id=subString[1].split("&")[0];
		if(id.length==11)
			return id;
		else
			return false;
	}
	return false;
}
function loadNewVideo() {
	var videoId=getVideoIdFromString(Utils.gebi('videoLink').value);
	if(videoId){
		ytplayer = Utils.gebi("myytplayer");
		if (ytplayer) {
			ytplayer.loadVideoById(videoId, 0);
		}
		else{
			var params = { allowScriptAccess: "always", bgcolor: "#cccccc" ,wmode:"transparent"};
			var atts = { id: "myytplayer" };
			swfobject.embedSWF("http://www.youtube.com/v/"+videoId+"&enablejsapi=1","ytapiplayer","200", "200", "8", null, null, params, atts);
		}
		$('#myytplayer').height(200);
	}
	else
		alert("bad url");
}

function sendVideo(){
	var videoId=getVideoIdFromString(Utils.gebi('videoLink').value);
	if(videoId){
		sendYouTube(Utils.gebi('videoText').value,videoId);
		$("#sendYouTube").dialog("close");
		Utils.gebi('videoLink').value='';
		Utils.gebi('videoText').value='';
		$('#myytplayer').height(0);
	}
	else
		alert("bad url");
}

function handleInputText(obj,e){
	if (!e) e=event;
	if ((e.keyCode==13)&&(e.shiftKey)){
		sendMessage();
        return false;
    }
    return true;
}


function onCreate(userObj){
		$('#notLoggedIn').dialog({ 
					autoOpen: false, 
					modal: true, 
					bgiframe: true,
					beforeclose : function(){ return false;} 
				});
		if (!userObj.loggedIn){
			$(document).ready(function(){
				$('#startLoadingImage').hide();
				$('#notLoggedIn').dialog('open'); 
			});
			return false;
			
		}
	
	
		var onRoomCreate = function(roomObj){
			var tabId=roomObj.tab.getContentContainer().id;
			setScrollEvent(tabId);
		}
		
        feed=new FeedRoom(onRoomCreate,userObj,renderGeneralMessages,"Feed");
		
		//clean unexisting rooms from rooms list
		var _activeRooms=[];
		for (var i=0;i<userObj.activeRooms.length;i++){
			if (userObj.isRoomExists(userObj.activeRooms[i])) _activeRooms.push(userObj.activeRooms[i]);
		}		
		userObj.activeRooms=_activeRooms;
		Utils.setArray("rooms",_activeRooms);
		
        // Get the array of search terms entered by the user
        for (var i=0;i<userObj.activeRooms.length;i++){
            var roomId=userObj.activeRooms[i];
            var roomObj=new Room(onRoomCreate,userObj,renderGeneralMessages,null,roomId);
        }

		// If user have only one room, start within it,
		if (userObj.rooms.length==1&&userObj.activeRooms.length==0){
			openRoom(userObj.rooms[0].roomId);
		}
		
        
        $(document).ready(function(){
			$("input").attr({autocomplete:"off"});

			var friends=[];	for(friendId in userObj.friends){friends.push(userObj.friends[friendId]); }
			
			$('#tbFriends').autocomplete(friends, {
				minChars: 0,
				matchContains: true,
				width:280,
				autoFill: false,
				formatItem: function(row, i, max) {
					return ((row.thumbnail)?("<img src='"+row.thumbnail+"' class='thumbnailClass' />"):(""))+ row.name;
				},
				formatMatch: function(row, i, max) {
					return row.name;
				},
				formatResult: function(row) {
					return row.id;
				}
			});
			$("#tbFriends").result(function(event, data, formatted) {
				if (data){
					$('#tbHiddenFriends').val(data.id);
					$(this).val(data.name);
					inviteFriend();
				}
			});
			
			$('#tbHiddenFriends').hide();
			
			$("#frmFriendEmail").submit(inviteFriendWithEmail);
		
			$('#startLoadingContainer').hide();
			$('#notSupportedDiv').hide();
			$('#mainDiv').show(); 
			
			
			$("#addPoll").dialog({ autoOpen: false, modal: true, resizable:false,bgiframe: true } );
			$("#sendYouTube").dialog({ autoOpen: false, modal: true, resizable:false ,minHeight:390,height: 390,bgiframe: true} );
			$("#videoButton").click(showVideo);
			
			
            $("#addPollButton").click(togglePoll);
			
			$("#statisticsButton").click(showStatistics);
			$("#statView").dialog({ autoOpen: false, modal: true, resizable:false,height:350,bgiframe: true } );
			
			$("#deleteRoomDialog").dialog({ autoOpen: false, modal: true, resizable:false ,bgiframe: true} );
			$("#deleteButton").click(function(){ removeRoom(false); });
			$("#deleteConfirm").click(function(){ removeRoom(true); });
			$("#deleteReject").click(function(){ $("#deleteRoomDialog").dialog("close"); });
			
			$("#nicknameChange").dialog({ autoOpen: false, modal: true, resizable:false,bgiframe: true } );
			$("#nicknameConfirm").click(function(){ changeNickname($('#nicknameText').val()); });
			$("#nicknameReject").click(function(){ changeNickname(false); });
			
			$("#approveWrap").dialog({ autoOpen: false, modal: true , resizable:false,bgiframe: true} );
			$("#approveClose").click(function(){$("#approveWrap").dialog("close"); });
			$("#emailsWrap").dialog({ autoOpen: false, modal: true , resizable:false,bgiframe: true} );
			
			$("#messageInputText").focus(function(){
				if ($(this).hasClass("nonActiveWrite")){
					$(this).val('');
					 $(this).removeClass("nonActiveWrite");
					 $(this).addClass("activeWrite");
				 }
            });
			$("#messageInputText").blur(function(){
				if ($(this).val()==''){
					$(this).removeClass("activeWrite");
					$(this).addClass("nonActiveWrite");
					$(this).val('Message');
				}
            });
			$("#messageInputText").keypress(function(){
				if ($(this).hasClass("nonActiveWrite")){
					$(this).val('');
					 $(this).removeClass("nonActiveWrite");
					 $(this).addClass("activeWrite");
				 }
            });
		});
    }


function OnLoadVideo() { 
  var searchControl = new google.search.SearchControl();
  options = new google.search.SearcherOptions();
  options.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN);
  var videoSearch = new google.search.VideoSearch();
  videoSearch.setResultOrder(google.search.Search.ORDER_BY_RELEVANCE);

  // Add our searcher to the control
  searchControl.addSearcher(videoSearch, options);

  // Draw the control onto the page
  searchControl.draw(document.getElementById("content"));
	$(".gsc-control").css("width","250px");
  // Because laughing is healthy.
 // searchControl.execute("funny");
 searchControl.setSearchCompleteCallback(null, 
    function() { 
      if (videoSearch.results[0]) { 
		
		$(".gs-publisher > a").attr("href",function() { 
          if(this.innerHTML=="www.youtube.com")
		  {
			var vidId=getVideoIdFromString1($(this).parent().parent().html());
			this.innerHTML="Select this video";
			$(this).click(function () { 
				loadNewVideoByVal(vidId);
				});
			$(this).css("border","black thin solid");	
			$(this).css("color","white");				
			$(this).css("background-color","#5C74A3");
			$(this).css("font-weight","bold");
			$(this).css("padding","1px 5px");
			
		  }
		  else{
				this.innerHTML="Not YouTube";
				$(this).click(function(){});
		  		
		  }
		 $(this).removeAttr("target");
		 $(this).removeAttr("href");
		 
        });
    }}); 
}

function getVideoIdFromString1(str)
{
	var subString=str.split("v%3D");
	if(subString.length>1){
		var id=subString[1].split("&")[0];
		if(id.length==11)
			return id;
		else
			return false;
	}
	return false;
}
function loadNewVideoByVal(videoId) {
	if(videoId){
		ytplayer = Utils.gebi("myytplayer");
		if (ytplayer) {
			ytplayer.loadVideoById(videoId, 0);
		}
		else{
			var params = { allowScriptAccess: "always", bgcolor: "#cccccc" ,wmode:"transparent"};
			var atts = { id: "myytplayer" };
			swfobject.embedSWF("http://www.youtube.com/v/"+videoId+"&enablejsapi=1","ytapiplayer","200", "200", "8", null, null, params, atts);
		}
		$('#myytplayer').height(200);
		Utils.gebi('videoLink').value="v="+videoId;
	}
	else
		alert("bad url");
}